
package com.afd.ozblip.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afd.ozblip.app.CommonInfo;
import com.afd.ozblip.entity.UserEntity;
import com.afd.ozblip.image.LoadImage;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.photo.PhotoIntentHelper;
import com.afd.ozblip.photo.TempFileProvider;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.util.SharedUtil;
import com.afd.ozblip.util.StringUtil;
import com.afd.ozblip.util.ToastUtils;
import com.afd.ozblip.view.MMAlert;
import com.google.zxing.client.android.CaptureCodeActivity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class UserCenterFragment extends Fragment {

    /****************** 视图变量 **************************/
    private LinearLayout userMainLayout;
    private ImageView userImageIv;
    private TextView userNameTv;
    private TextView userLevelTv;
    private TextView userPointTv;
    private EditText userSignatureEt;
    private ImageView userSignatureIv;
    private LinearLayout toLoginLayout;
    private LinearLayout toRegisterLayout;
    private LinearLayout vipLayout;
    private LinearLayout couponLayout;
    private LinearLayout collectLayout;
    private LinearLayout signLayout;
    private LinearLayout reviewLayout;
    private LinearLayout draftsterLayout;
    private LinearLayout photoLayout;
    private LinearLayout integralLayout;
    private LinearLayout messageLayout;
    private LinearLayout contactsLayout;
    private LinearLayout commonRight;
    /****************** 数据变量 **************************/
    private String fileBase64;
    private Bitmap headBitmap;
    private String signatureStr;
    /****************** 其它变量 **************************/
    private IndexActivity mActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mActivity = (IndexActivity) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity 必须是 "
                    + IndexActivity.class.getName());
        }
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        final View mainView = inflater.inflate(
                R.layout.user_center, container, false);
        this.userMainLayout = (LinearLayout) mainView.findViewById(R.id.ll_user_center_main);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        if (CommonInfo.isLogin) {
            final View logined = inflater.inflate(R.layout.user_info_logined, null);
            this.userMainLayout.addView(logined, lp);
            findLoginedViews(logined);
            setLoginedListeners();
            setLoginedView();
            return mainView;
        } else {
            final View unlogin = inflater.inflate(R.layout.user_info_unlogin, null);
            this.userMainLayout.addView(unlogin, lp);
            // 寻找视图
            findViews(unlogin);
            // 设置监听
            setListeners();
            return mainView;
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        // 刷新当前视图
        refreshView();

    }

    // 刷新当前视图
    void refreshView() {
        LayoutInflater inflater = LayoutInflater.from(mActivity);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        this.userMainLayout.removeAllViews();
        if (CommonInfo.isLogin) {
            final View logined = inflater.inflate(R.layout.user_info_logined, null);
            this.userMainLayout.addView(logined, lp);
            findLoginedViews(logined);
            setLoginedListeners();
            setLoginedView();
        } else {
            final View unlogin = inflater.inflate(R.layout.user_info_unlogin, null);
            this.userMainLayout.addView(unlogin, lp);
            // 寻找视图
            findViews(unlogin);
            // 设置监听
            setListeners();
        }
    }

    /**
     * 寻找未登录页面视图
     */
    public void findViews(View view) {
        this.toLoginLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_toLogin_btn);
        this.toRegisterLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_toRegister_btn);
        this.vipLayout = (LinearLayout) view.findViewById(R.id.ll_user_vip);
        this.couponLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_coupon);
        this.collectLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_collect);
        this.signLayout = (LinearLayout) view.findViewById(R.id.ll_user_sign);
        this.reviewLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_review);
        this.draftsterLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_drafts);
        this.photoLayout = (LinearLayout) view.findViewById(R.id.ll_user_photo);
        this.integralLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_integral);
        this.messageLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_message);
    }

    /**
     * 设置未登录页面监听
     */
    public void setListeners() {
        View.OnClickListener unLoginClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.ll_user_toLogin_btn:
                        Intent loginIntent = new Intent(mActivity,
                                LoginActivity.class);
                        // startActivity(loginIntent);
                        mActivity.startActivityForResult(loginIntent, 500);
                        break;
                    case R.id.ll_user_toRegister_btn:
                        Intent registerIntent = new Intent(
                                mActivity, RegisterActivity.class);
                        startActivity(registerIntent);
                        break;
                    case R.id.ll_user_vip:
                    case R.id.ll_user_coupon:
                    case R.id.ll_user_collect:
                    case R.id.ll_user_sign:
                    case R.id.ll_user_review:
                    case R.id.ll_user_drafts:
                    case R.id.ll_user_photo:
                    case R.id.ll_user_integral:
                    case R.id.ll_user_message:
                        ToastUtils.showShortToast(mActivity, "温馨提示：请先登录");
                        break;

                    default:
                        break;
                }
            }
        };
        this.toLoginLayout.setOnClickListener(unLoginClick);
        this.toRegisterLayout.setOnClickListener(unLoginClick);
        this.vipLayout.setOnClickListener(unLoginClick);
        this.couponLayout.setOnClickListener(unLoginClick);
        this.collectLayout.setOnClickListener(unLoginClick);
        this.signLayout.setOnClickListener(unLoginClick);
        this.reviewLayout.setOnClickListener(unLoginClick);
        this.draftsterLayout.setOnClickListener(unLoginClick);
        this.photoLayout.setOnClickListener(unLoginClick);
        this.integralLayout.setOnClickListener(unLoginClick);
        this.messageLayout.setOnClickListener(unLoginClick);

    }

    /**
     * TODO 寻找登录页面视图
     */
    public void findLoginedViews(View view) {
        this.commonRight = (LinearLayout) view
                .findViewById(R.id.ll_common_right);
        this.userImageIv = (ImageView) view.findViewById(R.id.iv_user_image);
        this.userNameTv = (TextView) view.findViewById(R.id.tv_user_name);
        this.userLevelTv = (TextView) view.findViewById(R.id.tv_user_level);
        this.userPointTv = (TextView) view.findViewById(R.id.tv_user_point);
        this.userSignatureEt = (EditText) view.findViewById(R.id.et_user_signature);
        this.userSignatureIv = (ImageView) view.findViewById(R.id.iv_user_signature);
        this.vipLayout = (LinearLayout) view.findViewById(R.id.ll_user_vip);
        this.couponLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_coupon);
        this.collectLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_collect);
        this.signLayout = (LinearLayout) view.findViewById(R.id.ll_user_sign);
        this.reviewLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_review);
        this.draftsterLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_drafts);
        this.photoLayout = (LinearLayout) view.findViewById(R.id.ll_user_photo);
        this.integralLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_integral);
        this.messageLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_message);
        this.contactsLayout = (LinearLayout) view
                .findViewById(R.id.ll_user_contacts);
    }

    /**
     * 设置登录页面监听
     */
    public void setLoginedListeners() {
        View.OnClickListener loginedClick = new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String userId = CommonInfo.commonUserInfo.getUserId();
                switch (v.getId()) {
                    case R.id.iv_user_image:
                        showImageMenuDialog();
                        break;
                    case R.id.iv_user_signature:
                        userSignatureEt.setEnabled(true);
                        userSignatureEt.setFocusable(true);
                        userSignatureEt.setFocusableInTouchMode(true);
                        userSignatureEt.requestFocus();
                        break;
                    case R.id.ll_user_vip:
                        Intent vipListIntent = new Intent(mActivity,
                                UserVipListActivity.class);
                        startActivity(vipListIntent);
                        break;
                    case R.id.ll_user_coupon:
                        Intent couponIntent = new Intent(mActivity,
                                UserCouponActivity.class);
                        startActivity(couponIntent);
                        break;
                    case R.id.ll_user_collect:
                        Intent collectIntent = new Intent(mActivity,
                                UserCollectActivity.class);
                        collectIntent.putExtra("userId", userId);
                        startActivity(collectIntent);
                        break;
                    case R.id.ll_user_sign:
                        Intent signedIntent = new Intent(mActivity,
                                UserSignedActivity.class);
                        signedIntent.putExtra("userId", userId);
                        startActivity(signedIntent);
                        break;
                    case R.id.ll_user_review:
                        Intent reviewIntent = new Intent(mActivity,
                                UserReviewListActivity.class);
                        reviewIntent.putExtra("userId", userId);
                        startActivity(reviewIntent);
                        break;
                    case R.id.ll_user_drafts:
                        Intent draftsIntent = new Intent(mActivity,
                                UserDraftsActivity.class);
                        startActivity(draftsIntent);
                        // startActivityForResult(draftsIntent, 1);
                        break;
                    case R.id.ll_user_photo:
                        Intent photoIntent = new Intent(mActivity,
                                UserPhotoActivity.class);
                        photoIntent.putExtra("userId", userId);
                        startActivity(photoIntent);
                        break;
                    case R.id.ll_user_integral:
                        Intent integralIntent = new Intent(
                                mActivity,
                                UserIntegralActivity.class);
                        startActivity(integralIntent);
                        break;
                    case R.id.ll_user_message:
                        Intent messageIntent = new Intent(mActivity,
                                UserMsgListActivity.class);
                        startActivity(messageIntent);
                        break;
                    case R.id.ll_user_contacts:
                        Intent contactsIntent = new Intent(
                                mActivity,
                                UserContactsActivity.class);
                        startActivity(contactsIntent);
                        break;
                    case R.id.ll_common_right:
                        CommonInfo.isLogin = false;
                        CommonInfo.commonUserInfo = null;
                        // 清除存储的信息
                        SharedUtil.clearUserInfo(mActivity);
                        // 刷新当前视图
                        refreshView();
                        break;

                    default:
                        break;
                }
            }
        };
        this.userImageIv.setOnClickListener(loginedClick);
        this.userSignatureIv.setOnClickListener(loginedClick);
        this.vipLayout.setOnClickListener(loginedClick);
        this.couponLayout.setOnClickListener(loginedClick);
        this.collectLayout.setOnClickListener(loginedClick);
        this.signLayout.setOnClickListener(loginedClick);
        this.reviewLayout.setOnClickListener(loginedClick);
        this.draftsterLayout.setOnClickListener(loginedClick);
        this.photoLayout.setOnClickListener(loginedClick);
        this.integralLayout.setOnClickListener(loginedClick);
        this.messageLayout.setOnClickListener(loginedClick);
        this.commonRight.setOnClickListener(loginedClick);
        this.contactsLayout.setOnClickListener(loginedClick);

        this.userSignatureEt
                .setOnEditorActionListener(new TextView.OnEditorActionListener() {

                    @Override
                    public boolean onEditorAction(TextView v, int actionId,
                            KeyEvent event) {
                        signatureStr = userSignatureEt.getText().toString();
                        requestUpdateUserData();
                        return false;
                    }
                });

    }

    /**
     * 设置登录后界面视图
     */
    private void setLoginedView() {
        UserEntity commonUserInfo = CommonInfo.commonUserInfo;
        if (commonUserInfo != null) {
            String headUrl = commonUserInfo.getUserHeadUrl();
            if (!StringUtil.isNullOrEmpty(headUrl)) {
                LoadImage li = new LoadImage(mActivity);
                li.addTask(Constants.WEB_PATH + headUrl, this.userImageIv);
            }
            String nickName = commonUserInfo.getUserNickName();
            if (!StringUtil.isNullOrEmpty(nickName)) {
                this.userNameTv.setText(nickName);
            }
            String userLevel = commonUserInfo.getUserLevel();
            if (!StringUtil.isNullOrEmpty(userLevel)) {
                this.userLevelTv.setText(userLevel);
            }
            String userPoint = commonUserInfo.getUserIntegral();
            if (!StringUtil.isNullOrEmpty(userPoint)) {
                this.userPointTv.setText(userPoint);
            }
            String userSignature = commonUserInfo.getUserSignature();
            if (!StringUtil.isNullOrEmpty(userSignature)) {
                this.userSignatureEt.setText(userSignature);
            }

        }
    }

    private static final int REQUEST_CAPTURE_IMAGE = 20121;
    private static final int REQUEST_SELECT_IMAGE = 20122;
    private static final int REQUEST_CROP_IMAGE = 20123;

    private void showImageMenuDialog() {
        MMAlert.showAlert(mActivity, "",
                new String[] {
                        "相机拍摄", "手机相册"
                }, null,
                new MMAlert.OnAlertSelectId() {

                    @Override
                    public void onClick(int whichButton) {
                        switch (whichButton) {
                            case 0:
                                startActivityForResult(
                                        PhotoIntentHelper
                                                .getCaptureImageIntent(mActivity),
                                        REQUEST_CAPTURE_IMAGE);
                                break;
                            case 1:
                                startActivityForResult(
                                        PhotoIntentHelper.getSelectImageIntent(mActivity),
                                        REQUEST_SELECT_IMAGE);
                                break;
                        }
                    }

                });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
        // 拍照
        // /////////////////////////////////////////
            case REQUEST_CAPTURE_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    final File file = new File(TempFileProvider.getTempFilePath(
                            mActivity, TempFileProvider.CODE_CAPTURE_IMAGE));
                    cropImage(Uri.fromFile(file));
                }
                break;
            // 选择照片
            // /////////////////////////////////////////
            case REQUEST_SELECT_IMAGE:
                if (resultCode == Activity.RESULT_OK && data != null) {
                    cropImage(data.getData());
                }
                break;
            // 裁剪照片
            // /////////////////////////////////////////
            case REQUEST_CROP_IMAGE:
                if (resultCode == Activity.RESULT_OK) {
                    setUserImage(TempFileProvider.getTempFilePath(mActivity,
                            TempFileProvider.CODE_CROP_IMAGE));
                }
                break;
        }
    }

    /**
     * 裁剪图片
     * 
     * @param uri
     */
    private void cropImage(Uri uri) {
        startActivityForResult(PhotoIntentHelper.getCropUserAvatarIntent(
                mActivity, uri, TempFileProvider.CONTENT_URI_CROP_IMAGE),
                REQUEST_CROP_IMAGE);
    }

    /**
     * 裁剪图片
     * 
     * @param uri
     */
    private void setUserImage(String imgPath) {
        // 将字节数组转换为ImageView可调用的Bitmap对象
        headBitmap = BitmapFactory.decodeFile(imgPath);
        userImageIv.setImageBitmap(headBitmap);
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        headBitmap.compress(CompressFormat.JPEG, 100, bStream);
        byte[] bytes = bStream.toByteArray();
        fileBase64 = Base64.encodeToString(bytes, Base64.DEFAULT);
        requestUpdateUserData();

    }

    /**
     * 获取评论列表数据
     */
    private void requestUpdateUserData() {
        if (CommonInfo.commonUserInfo == null) {
            return;
        }
        AsyncLoadData ald = new AsyncLoadData(mActivity, "修改中...",
                new AsyncAction() {

                    @Override
                    public void doLoad() throws Exception {
                        // 获取提交参数
                        Map<String, Object> nearbyBusinessParamMap = new HashMap<String, Object>();
                        nearbyBusinessParamMap.put("userId",
                                CommonInfo.commonUserInfo.getUserId());
                        nearbyBusinessParamMap.put("headImg", fileBase64);
                        nearbyBusinessParamMap.put("signature", signatureStr);
                        // 发送请求
                        byte[] commentItemList = HttpUtil.requestByPost(
                                mActivity,
                                Constants.UPDATE_USER_API,
                                nearbyBusinessParamMap);
                        if (commentItemList != null) {
                            new ParseJson().parseAddResultJson(commentItemList);
                        }
                    }

                    @Override
                    public void loadEnd() throws Exception {
                        userSignatureEt.setFocusable(false);
                    }

                });
        ald.execute(0);
    }
}
